package com.xcode.socket.udp;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class SocketUDPServer
{
	private byte[] buff= null;
	private DatagramPacket packet = null;
	private DatagramSocket server = null;
	private onMessageListener listener = null;
	private boolean loop = false;
	Thread thread = new Thread()
	{
		public void run() 
		{
			try
			{
				while (loop)
				{
					if (server != null)
					{
						server.receive(packet);
						byte []data = packet.getData();
						byte []msg = new byte[packet.getLength()];
						for (int i = 0; i < msg.length; i++)
						{
							msg[i] = data[i];
						}
						if (listener != null)
						{
							listener.OnMessage(msg,packet.getAddress().getHostAddress(),packet.getPort());
						}
					}
				}
			} catch (Exception e)
			{
			}
		};
	};
	/**
	 * 构造函数 初始化数据
	 * @param port		端口
	 * @param size		缓冲区的长度
	 * @throws Exception
	 */
	public SocketUDPServer(int port) throws Exception
	{
		try
		{
			buff= new byte[1471];
			packet = new DatagramPacket(buff, buff.length);
			server = new DatagramSocket(port);
		} catch (Exception e)
		{
			throw e;
		}
	}
	/**
	 * 设置数据的获取者
	 * @param listener
	 */
	public SocketUDPServer setOnMessageListener(onMessageListener listener)
	{
		this.listener = listener;
		return this;
	}
	/**
	 * 开始接收数据
	 */
	public void start()
	{
		loop = true;
		if (!thread.isAlive())
		{
			thread.start();
		}
	}
	/**
	 * 关闭流  释放资源
	 */
	public void close()
	{
		loop = false;
		if (server != null)
		{
			server.close();
			server = null;
		}
	}
}
